<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useContextMenu } from './ContextMenu'


const props = defineProps({
  menu: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['select'])
const handleClick = (item) => {
  visible.value = false
  emit('select', item)
}

const contextMenuRef = ref(null)
// const x = ref(0)
// const y = ref(0)
// const visible = ref(false)
const { x, y, visible } = useContextMenu(contextMenuRef)
onMounted(() => {
  // x.value = x
  // y.value = y
  // visible.value = visible
})

const handelBeforeEnter = (el) => {
  el.style.height = 0
}
const handeEnter = (el) => {
  el.style.height = 'auto'
  const h = el.clientHeight
  el.style.height = 0
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      el.style.height = h + 'px'
      el.style.transition = '0.5s'
    })
  })
}
const handeAfterEnter = (el) => {
  el.style.transition = 'none'
}
</script>

<template>
  <div class="container" ref="contextMenuRef">
    <slot></slot>
    <Teleport to="body">
      <Transition @beforeEnter="handelBeforeEnter" @enter="handeEnter" @afterEnter="handeAfterEnter">
        <div class="contextMenu" v-if="visible" :style="{ top: y + 'px', left: x + 'px' }">
          <div class="menuList">
            <div class="menuItem" v-for="(item, index) in menu" :key="index" @click="handleClick(item)">
              {{ item.label }}
            </div>
          </div>
        </div>
      </Transition>

    </Teleport>
  </div>
</template>

<style>
.contextMenu {
  position: fixed;
  padding: 10px 5px;
  width: 100px;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
}

.menuList {
  width: 100%;
  height: 100%;
}

.menuItem {
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
}

.menuItem:hover {
  background: #61afef;
  color: #fff;
}
</style>
<style scoped></style>
